package jnpf.permission.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jnpf.base.Pagination;
import jnpf.database.util.DataSourceUtil;
import jnpf.permission.constant.PermissionConst;
import jnpf.permission.entity.OrganizeAdministratorEntity;
import jnpf.permission.entity.OrganizeEntity;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.entity.UserRelationEntity;
import jnpf.permission.mapper.OrganizeAdminIsTratorMapper;
import jnpf.permission.model.organizeadministrator.OrganizeAdministratorListVo;
import jnpf.permission.service.OrganizeAdministratorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.permission.service.OrganizeService;
import jnpf.permission.service.UserRelationService;
import jnpf.permission.service.UserService;
import jnpf.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 机构分级管理员
 *
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date 2019年9月26日 上午9:18
 */
@Service
public class OrganizeAdministratorServiceImpl extends ServiceImpl<OrganizeAdminIsTratorMapper, OrganizeAdministratorEntity> implements OrganizeAdministratorService {

    @Autowired
    private UserProvider userProvider;
    @Autowired
    private OrganizeService organizeService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserRelationService userRelationService;
    @Autowired
    private DataSourceUtil dataSourceUtil;


    @Override
    public OrganizeAdministratorEntity getOne(String userId, String organizeId) {
        QueryWrapper<OrganizeAdministratorEntity> queryWrapper = new QueryWrapper<>();
        if ("Oracle".equals(dataSourceUtil.getDbType()) || "DM".equals(dataSourceUtil.getDbType())) {
            queryWrapper.eq("dbms_lob.substr(F_USERID)", userId);
        } else {
            queryWrapper.lambda().eq(OrganizeAdministratorEntity::getUserId, userId);
        }
        queryWrapper.lambda().eq(OrganizeAdministratorEntity::getOrganizeId, organizeId);
        // 排序
        queryWrapper.lambda().orderByAsc(OrganizeAdministratorEntity::getSortCode)
                .orderByDesc(OrganizeAdministratorEntity::getCreatorTime);
        return this.getOne(queryWrapper);
    }

    @Override
    public List<OrganizeAdministratorEntity> getOrganizeAdministratorEntity(String userId) {
        QueryWrapper<OrganizeAdministratorEntity> queryWrapper = new QueryWrapper<>();
        if ("Oracle".equals(dataSourceUtil.getDbType()) || "DM".equals(dataSourceUtil.getDbType())) {
            queryWrapper.eq("dbms_lob.substr(F_USERID)", userId);
        } else {
            queryWrapper.lambda().eq(OrganizeAdministratorEntity::getUserId, userId);
        }
        // 排序
        queryWrapper.lambda().orderByAsc(OrganizeAdministratorEntity::getSortCode)
                .orderByDesc(OrganizeAdministratorEntity::getCreatorTime);
        List<OrganizeAdministratorEntity> list = this.list(queryWrapper);
        return list;
    }

    @Override
    @Transactional
    public void create(OrganizeAdministratorEntity entity) {
        // 判断是新建还是删除
        QueryWrapper<OrganizeAdministratorEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeAdministratorEntity::getOrganizeId, entity.getOrganizeId());
        if ("Oracle".equals(dataSourceUtil.getDbType()) || "DM".equals(dataSourceUtil.getDbType())) {
            queryWrapper.eq("dbms_lob.substr(F_USERID)", entity.getUserId());
        } else {
            queryWrapper.lambda().eq(OrganizeAdministratorEntity::getUserId, entity.getUserId());
        }
        // 查出数据是否重复
        OrganizeAdministratorEntity administratorEntity = this.getOne(queryWrapper);
        if (administratorEntity == null) {
            entity.setId(RandomUtil.uuId());
            entity.setCreatorUserId(userProvider.get().getUserId());
            entity.setCreatorTime(new Date());
        } else {
            entity.setId(administratorEntity.getId());
            entity.setCreatorUserId(userProvider.get().getUserId());
            entity.setLastModifyTime(new Date());
        }
        this.saveOrUpdate(entity);
    }

    @Override
    public boolean update(String organizeId, OrganizeAdministratorEntity entity) {
        entity.setId(entity.getId());
        entity.setLastModifyTime(DateUtil.getNowDate());
        entity.setLastModifyUserId(userProvider.get().getUserId());
        return this.updateById(entity);
    }

    @Override
    public boolean deleteByUserId(String userId) {
        QueryWrapper<OrganizeAdministratorEntity> queryWrapper = new QueryWrapper<>();
        if ("DM".equals(dataSourceUtil.getDbType())) {
            queryWrapper.eq("dbms_lob.substr(F_USERID)", userId);
        } else {
            queryWrapper.lambda().eq(OrganizeAdministratorEntity::getUserId, userId);
        }
        return this.remove(queryWrapper);
    }

    @Override
    public OrganizeAdministratorEntity getInfo(String id) {
        QueryWrapper<OrganizeAdministratorEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeAdministratorEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void delete(OrganizeAdministratorEntity entity) {
        this.removeById(entity.getId());
    }

    @Override
    public OrganizeAdministratorEntity getInfoByOrganizeId(String organizeId) {
        QueryWrapper<OrganizeAdministratorEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeAdministratorEntity::getOrganizeId, organizeId);
        return this.getOne(queryWrapper);
    }

    @Override
    public List<OrganizeAdministratorEntity> getListByOrganizeId(List<String> organizeIdList) {
        QueryWrapper<OrganizeAdministratorEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(OrganizeAdministratorEntity::getOrganizeId, organizeIdList);
        return this.list(queryWrapper);
    }

    @Override
    public List<OrganizeAdministratorListVo> getList(Pagination pagination) {
        List<OrganizeAdministratorEntity> list = getOrganizeAdministratorEntity(userProvider.get().getUserId());
        List<String> organizeIdList = new ArrayList<>(16);
        // 存放所有的有资格管理的组织id
        if (userProvider.get().getIsAdministrator()) {
            organizeIdList = organizeService.getListById(true).stream().map(OrganizeEntity::getId).collect(Collectors.toList());
        } else {
            Set<String> orgId = new HashSet<>(16);
            // 判断自己是哪些组织的管理员
            list.stream().forEach(t-> {
                if (t != null) {
                    // t.getThisLayerAdd() == 1 || t.getThisLayerEdit() == 1 || t.getThisLayerDelete() == 1 || (StringUtil.isNotEmpty(String.valueOf(t.getSubLayerSelect())) && t.getThisLayerSelect() == 1)
                    if (t.getSubLayerSelect() != null && t.getThisLayerSelect() == 1) {
                        orgId.add(t.getOrganizeId());
                    }
                    // t.getSubLayerAdd() == 1 || t.getSubLayerEdit() == 1 || t.getSubLayerDelete() == 1 || (StringUtil.isNotEmpty(String.valueOf(t.getSubLayerSelect())) && t.getSubLayerSelect() == 1)
                    if (t.getSubLayerSelect() != null && t.getSubLayerSelect() == 1) {
                        List<String> underOrganizations = organizeService.getUnderOrganizations(t.getOrganizeId());
                        orgId.addAll(underOrganizations);
                    }
                }
            });
            organizeIdList = new ArrayList<>(orgId);
        }
        if (organizeIdList.size() < 1) {
            organizeIdList.add("");
        }
        List<OrganizeAdministratorEntity> list1 = getListByOrganizeId(organizeIdList);
        List<String> userIdList = list1.stream().map(OrganizeAdministratorEntity::getUserId).distinct().collect(Collectors.toList());
        List<String> finalOrganizeIdList = organizeIdList;
        List<String> userLists = new ArrayList<>();
        List<String> finalUserLists = userLists;
        userIdList.forEach(t -> {
            List<String> collect = userRelationService.getListByUserId(t).stream().filter(ur -> PermissionConst.ORGANIZE.equals(ur.getObjectType())).map(UserRelationEntity::getObjectId).collect(Collectors.toList());
            List<String> collect1 = finalOrganizeIdList.stream().filter(collect::contains).collect(Collectors.toList());
            if (collect1.size() > 0) {
                finalUserLists.add(t);
            }
        });
        userLists = userLists.stream().distinct().collect(Collectors.toList());
        List<UserEntity> userList = userService.getUserNames(userLists, pagination, true);
        userList.forEach(t -> {
            // 创建时间
            Date date = getOrganizeAdministratorEntity(t.getId()).stream().sorted(Comparator.comparing(OrganizeAdministratorEntity::getCreatorTime)).map(OrganizeAdministratorEntity::getCreatorTime).findFirst().orElse(null);
            t.setCreatorTime(date);
            // 所属组织
            List<UserRelationEntity> orgRelationByUserId = userRelationService.getAllOrgRelationByUserId(t.getId());
            StringBuilder orgName = new StringBuilder();
            orgRelationByUserId.stream().forEach(or -> {
                OrganizeEntity organizeEntity = organizeService.getInfo(or.getObjectId());
                if (organizeEntity != null && StringUtil.isNotEmpty(organizeEntity.getOrganizeIdTree())) {
                    String fullNameByOrgIdTree = organizeService.getFullNameByOrgIdTree(organizeEntity.getOrganizeIdTree(), "/");
                    orgName.append("," + fullNameByOrgIdTree);
                }
            });
            // 组织名称
            String org = orgName.length() > 0 ? orgName.toString().replaceFirst(",", "") : "";
            t.setOrganizeId(org);
        });
        // 处理所属组织和创建时间
        List<OrganizeAdministratorListVo> jsonToList = JsonUtil.getJsonToList(userList, OrganizeAdministratorListVo.class);
        jsonToList = jsonToList.stream().filter(t -> t != null && t.getCreatorTime() != null).sorted(Comparator.comparing(OrganizeAdministratorListVo::getCreatorTime).reversed()).collect(Collectors.toList());
        return jsonToList;
    }

    @Override
    public List<OrganizeEntity> getListByAuthorize() {
        // 通过权限转树
        List<OrganizeAdministratorEntity> listss = getOrganizeAdministratorEntity(userProvider.get().getUserId());
        Set<String> orgIds = new HashSet<>(16);
        // 判断自己是哪些组织的管理员
        listss.stream().forEach(t-> {
            if (t != null) {
                if (t.getThisLayerSelect() != null && t.getThisLayerSelect() == 1) {
                    orgIds.add(t.getOrganizeId());
                }
                if (t.getSubLayerSelect() != null && t.getSubLayerSelect() == 1) {
                    List<String> underOrganizations = organizeService.getUnderOrganizations(t.getOrganizeId());
                    orgIds.addAll(underOrganizations);
                }
            }
        });
        List<String> list1 = new ArrayList<>(orgIds);
        // 得到所有有权限的组织
        List<OrganizeEntity> organizeName = organizeService.getOrganizeName(list1);
        return organizeName;
    }

    @Override
    public List<OrganizeAdministratorEntity> getListByUserID(String userID) {
        QueryWrapper<OrganizeAdministratorEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeAdministratorEntity::getUserId, userID);
        List<OrganizeAdministratorEntity> list = this.list(queryWrapper);
        return list;
    }

}
